Ext.onReady(function () {
	Ext.Loader.setConfig({enabled:true});
	Ext.getBody().on("contextmenu", Ext.emptyFn, null, {preventDefault: true});
	var win;
	var isLeaf;
	var nodeName;
	var parId;
	var tip;
	
	var showInfoFailure = function(form,action){
		if(action.result!=null) showErrorTip(infoPanel.body,action)
	}
	
	var showErrorTip = function(tipTarget, act){
		if(tip){
			tip.disable();
			tip = null;
		}
        tip = Ext.widget('tooltip', {
        	target: tipTarget,
            title: 'Error Details:',
            autoHide: false,
            anchor: 'top',
            html: act.result.error,
            closable: true,
            mouseOffset: [-11, 0],
            constrainPosition: false,
        });
        tip.show();
	}
	
	var sendFunction = function() {
		var newNodeCreate = function(form,action){
			var leafId = action.result.returnedId;
			if(isLeaf==true)
			{
				nodeName = addForm.getForm().findField('firstName').getValue() + 
				" " + addForm.getForm().findField('lastName').getValue();
			} else {
				nodeName = addForm.getForm().findField('name').getValue();
			}
			addTreeNode(nodeName, isLeaf, leafId, parId);
			if(tip){
				tip.disable();
				tip = null;
			}
			win.hide();
		}

		var showCreateFailure = function(form,action) {
			if(action.result!=null)
			showErrorTip(addForm.body, action);
		}
		var rec = treeCompany.getSelectionModel().getSelection()[0];
		parId = rec.get('id');
		
		addForm.getForm().submit({
			params : {parentid: parId},
			success : newNodeCreate,
			failure : showCreateFailure
		});
	}
	
	function addTreeNode(name, isleaf, lid, pid) {
		var rec = treeCompany.getSelectionModel().getSelection()[0];
		rec.appendChild(Ext.create('User',
			{
				text: name,
				leaf : isleaf,
				parentid: pid,
				id: lid
			})
		);
	}
	
	var sendButton = new Ext.Button({
        text: 'Send',
        handler: sendFunction
    });
	
	var resetButton = new Ext.Button({
        text: 'Reset',
        handler: function()
        {
            addForm.getForm().reset();
        }
     });
	
    var addForm = Ext.create('Ext.form.Panel', {
        layout: {
            type: 'vbox',
            align: 'stretch'
        },
        border: false,
        url: 'createData',
        id: 'addForm',
        bodyPadding: 10,
		method: 'POST',
        fieldDefaults: {
            labelAlign: 'top',
            labelWidth: 100,
            labelStyle: 'font-weight:bold'
        },
        defaults: {
            margins: '0 0 10 0'
        },

        buttons: [sendButton,resetButton]
    });
	    
    function showAddForm(selectionData) {
    	if(tip){
    		tip.disable();
    		tip = null;
    	}
       	win = Ext.widget('window', {
            title: 'Add',
            closeAction: 'hide',
            width: 400,
            height: 220,
            minHeight: 220,
            layout: 'fit',
            resizable: true,
            modal: true,
            items: addForm
        });
       	
    	switch (selectionData.split(" ")[0]) {
    		case "company" :
				addForm.removeAll();
				isLeaf = false;
		    	addForm.add([{
                    xtype: 'fieldcontainer',
                    fieldLabel: 'Unit',
                    labelStyle: 'font-weight:bold;padding:0',
                    layout: 'hbox',
                    defaultType: 'textfield',

                    fieldDefaults: {
                        labelAlign: 'top'
                    },

                    items: [{
                        flex: 1,
                        name: 'name',
                        fieldLabel: 'Name',
                        allowBlank: false
                    }]
                }]);
		        break;
		    case "unit":
				addForm.removeAll();
				isLeaf = false;
		    	addForm.add([{
                    xtype: 'fieldcontainer',
                    fieldLabel: 'Project',
                    labelStyle: 'font-weight:bold;padding:0',
                    layout: 'hbox',
                    defaultType: 'textfield',

                    fieldDefaults: {
                        labelAlign: 'top'
                    },

                    items: [{
                        flex: 1,
                        name: 'name',
                        fieldLabel: 'Name',
                        allowBlank: false
                    }]
                }]);
		       	break;
		    case "project":
		    	addForm.removeAll();
		    	isLeaf = true;
		    	addForm.add([{
	                    xtype: 'fieldcontainer',
	                    fieldLabel: 'Name',
	                    labelStyle: 'font-weight:bold;padding:0',
	                    layout: 'hbox',
	                    defaultType: 'textfield',
	
	                    fieldDefaults: {
	                        labelAlign: 'top'
	                    },
	
	                    items: [{
	                        flex: 1,
	                        name: 'firstName',
	                        fieldLabel: 'First',
	                        allowBlank: false
	                    }, {
	                        flex: 2,
	                        name: 'lastName',
	                        fieldLabel: 'Last',
	                        allowBlank: false,
	                        margins: '0 0 0 5'
	                    }]
                	}, {
	                    xtype: 'textfield',
	                    fieldLabel: 'Email Address',
	                    name:'email',
	                    vtype: 'email',
	                    allowBlank: false
                	}]
		    	);
		    	addForm.add(tabPanel);
		    	win.setHeight(500);
		    	break;
		    default:
		        break;
			}
    		win.show();
		}

	Ext.regModel('treeModel', {
		fields: ['id', 'text', 'parentid']
	});
	
	storeTree = Ext.create('Ext.data.TreeStore', {
		model: 'treeModel',
		sortOnLoad : true,
		proxy: {
			model: 'treeModel',
			type: 'ajax',
			url: 'getJson',
	        reader: 'json',
	        root: 'root'
		}
	});
	
	var addItem = Ext.create('Ext.Action', {
		iconCls: 'buy-button',
		text: 'Add Item',
        handler: function(widget, event) {
			var rec = treeCompany.getSelectionModel().getSelection()[0];
    		if (rec) {
				showAddForm(rec.get('id'));
        	}
        }
	});

	var deleteItem = Ext.create('Ext.Action', {
        text: 'Delete Item',
        iconCls: 'buy-button',
        handler: function(widget, event) {
			var rec = treeCompany.getSelectionModel().getSelection()[0];
    		if (rec) {
    		rec.remove();
    		Ext.Ajax.request({
				url : 'deleteData' , 
				params : { node : rec.get('id') },
				method: 'GET',
			});						
			}
        }
	}); 
   	
	var contextMenu = Ext.create('Ext.menu.Menu', {
		items: [
    		addItem,
    		deleteItem,
		]
	});
	
   	Ext.regModel('User', {
		fields: ['id', 'firstName', 'lastName', 'parentid']
	});
	
	
	storeUser = Ext.create('Ext.data.Store', {
		model: 'User',
		proxy: {
      		type: 'ajax',
      		url: 'getJson?cell=',
      		reader: {
          		type: 'json',
      		}
    	}
	});
	
    treeCompany = Ext.create('Ext.tree.Panel', {
        title: 'Company Structure',
        rootVisible: false,
        store: storeTree,
        split: true,
        region: 'west',
        editable : true,
        layout: 'fit',
        root: {text: 'Service',
			id: 'root',
		},
        frame: true,
        collapsible: true,
        floatable: false,
        width: 200,
        listeners: {
       		itemclick: {
           		fn: function(view, record, item, index, event) {
           			switch (record.data.id.split(" ")[0])
           			{
	           			case "user":
		                    infoPanel.getForm().reader = userInfoReader;
		                    infoPanel.getForm().load({
		                        url: 'getJson?cell='+ record.data.id,
		                        waitMsg: 'Loading...'
		                    });
		                    infoPanel.removeAll();
		                    infoPanel.add([userMainInfo,tabPanel]);
		                    break;
	           			case "project":
		                    infoPanel.getForm().reader = commonInfoReader;
		                    infoPanel.getForm().load({
		                        url: 'getJson?cell='+ record.data.id,
		                        waitMsg: 'Loading...'
		                    });
		                    infoPanel.removeAll();
		                    infoPanel.add(projectInfo);
		                    break;
	           			case "unit":
		                    infoPanel.getForm().reader = commonInfoReader;
		                    infoPanel.getForm().load({
		                        url: 'getJson?cell='+ record.data.id,
		                        waitMsg: 'Loading...'
		                    });
		                    infoPanel.removeAll();
		                    infoPanel.add(unitInfo);
		                    break;
	           			case "company":
		                    infoPanel.getForm().reader = commonInfoReader;
		                    infoPanel.getForm().load({
		                        url: 'getJson?cell='+ record.data.id,
		                        waitMsg: 'Loading...'
		                    });
		                    infoPanel.removeAll();
		                    infoPanel.add(companyInfo);
		                    break;
		                default:
		                	infoPanel.removeAll();
	                    	break;
           			}
            	}
        	},
        	itemcontextmenu: {
        		fn: function(view,record,item,index, e) {
					e.stopEvent();
					var rec = treeCompany.getSelectionModel().getSelection()[0];
					switch (rec.get('id').split(" ")[0]) {
						case "company":
	                    	addItem.setText("Add Unit");
	    					contextMenu.removeAll();		                    	
	    					contextMenu.add([
	    				    					addItem,
	    									]);	                    	
	                    	break;
	                    case "unit":
	                    	addItem.setText("Add Project");
	    					contextMenu.removeAll();		                    	
	    					contextMenu.add([
	    				    					addItem,
	    				    					deleteItem,
	    									]);	                    	
	                    	break;
	                    case "project":
	                    	addItem.setText("Add Person");
	    					contextMenu.removeAll();		                    	
	    					contextMenu.add([
	    				    					addItem,
	    				    					deleteItem,
	    									]);	                    	
	                    	break;
	                    case "user":
	                    	contextMenu.removeAll();
		                   	contextMenu.add([
            					deleteItem,
        					]);
	                    	break;
	                    default:
					}
					contextMenu.showAt(e.getXY());
						

        		}
        	}
        }
    });
    
    var tabPanel = {
            xtype:'tabpanel',
            plain:true,
            activeTab: 0,
            height:235,
            defaults:{bodyStyle:'padding:10px'},
            items:[{
                title:'Phone Numbers',
                defaults: {width: 230},
                defaultType: 'textfield',

                items: [{
                    fieldLabel: 'Home',
                    name: 'home',
                    allowBlank: false
                },{
                    fieldLabel: 'Mobile',
                    name: 'mobile',
                    allowBlank: false
                }]
            },{
                cls: 'x-plain',
                title: 'Biography',
                layout: 'fit',
                items: {
                    xtype: 'htmleditor',
                    name: 'bio2',
                    fieldLabel: 'Biography',
                    allowBlank: true
                }
            }]
    }
    
    Ext.define('userModel', {
        extend: 'Ext.data.Model',
        fields: ['id', 'firstName', 'lastName','projectName', 'email','bio2','home','mobile']
    });
    
    Ext.define('commonModel', {
    	 extend: 'Ext.data.Model',
         fields: ['id', 'name', 'parentName']
    });
    
    var commonInfoReader = Ext.create('Ext.data.reader.Json', {
        model: 'commonModel'
    });
    
    var userInfoReader = Ext.create('Ext.data.reader.Json', {
        model: 'userModel'
    });

    var unitInfo = {
    		layout:'column',
		    border:false,
		    items:[{
		        columnWidth:.5,
		        border:false,
		        layout: 'anchor',
		        defaultType: 'textfield',
		        items: [{
		            fieldLabel: 'Unit Name',
		            name: 'name',
		            anchor:'95%'
		        }, {
		            fieldLabel: 'Company',
		            name: 'parentName',
		            disabled: true,
		            anchor:'95%'
		        }]
		    }]
    }
    
    var companyInfo = {
    		layout:'column',
		    border:false,
		    items:[{
		        columnWidth:.5,
		        border:false,
		        layout: 'anchor',
		        defaultType: 'textfield',
		        items: [{
		            fieldLabel: 'Company Name',
		            name: 'name',
		            anchor:'95%'
		        }]
		    }]
    }
    
    var projectInfo = {
    		layout:'column',
		    border:false,
		    items:[{
		        columnWidth:.5,
		        border:false,
		        layout: 'anchor',
		        defaultType: 'textfield',
		        items: [{
		            fieldLabel: 'Project Name',
		            name: 'name',
		            anchor:'95%'
		        }, {
		            fieldLabel: 'Unit',
		            name: 'parentName',
		            disabled: true,
		            anchor:'95%'
		        }]
		    }]
    }
    
    var userMainInfo = {
            layout:'column',
            border:false,
            items:[{
                columnWidth:.5,
                border:false,
                layout: 'anchor',
                defaultType: 'textfield',
                items: [{
                    fieldLabel: 'First Name',
                    name: 'firstName',
                    anchor:'95%'
                }, {
                    fieldLabel: 'Project',
                    name: 'projectName',
                    disabled: true,
                    anchor:'95%'
                }]
            },{
                columnWidth:.5,
                border:false,
                layout: 'anchor',
                defaultType: 'textfield',
                items: [{
                    fieldLabel: 'Last Name',
                    name: 'lastName',
                    anchor:'95%'
                },{
                    fieldLabel: 'Email',
                    name: 'email',
                    vtype:'email',
                    anchor:'95%'
                }]
            }]
        }
    
    var infoPanel = Ext.create('Ext.form.Panel', {
        title: 'Information',
        region:'center',
        bodyStyle:'padding:5px',
        width: 600,
        fieldDefaults: {
            labelAlign: 'top',
            msgTarget: 'side'
        },
        defaults: {
            anchor: '100%'
        },
        buttons: [{
            text: 'Apply Changes',
            handler: function(){
            	var rec = treeCompany.getSelectionModel().getSelection()[0];
				var sendNodeType = rec.get('id').split(" ")[0]
				var sendNodeId = rec.get('id').split(" ")[1]
				infoPanel.getForm().submit({
        			url: 'updateData',
        			params: {nodeType: sendNodeType, nodeId: sendNodeId},
					success: function(form,action){
						if(sendNodeType=="user")
						{
							var name = infoPanel.getForm().findField('firstName').getValue() + " "
							+ infoPanel.getForm().findField('lastName').getValue();
						} else {
							var name = infoPanel.getForm().findField('name').getValue();
						}	
						rec.set('text',name);
						rec.commit();
						if(tip){
							tip.disable();
							tip = null;
						}
					},
					failure: showInfoFailure
        		});
            }
        }]
    });
    
	Ext.create('Ext.window.Window', {
	    	title: 'Browser',
			height: 450,
			width: 700,
			layout: 'border',
			bodyStyle: 'padding: 5px',
			items: [treeCompany,infoPanel]
		}
	).show();
	
	treeCompany.getSelectionModel().on({
		selectionchange: function(sm, selections) {
        	if (selections.length) {
            	addItem.enable();
            	deleteItem.enable();
        	} else {
            	addItem.disable();
            	deleteItem.disable();
        	}
		}
	});
});